<template>
  <div class="forecast-container">
    <!-- 温度趋势图 -->
    <div class="chart-wrapper">
      <div ref="tempChartRef" class="temp-chart"></div>
    </div>

    <!-- 天气预报列表 -->
    <div class="forecast-wrapper">
      <div class="forecast-list">
        <div v-for="forecast in forecasts" :key="forecast.date" class="forecast-item">
          <div class="date">
            <div class="day">{{ formatDate(forecast.date).date }}</div>
            <div class="week">{{ forecast.week }}</div>
          </div>
          <div class="info-wrapper">
            <div class="left-info">
              <img :src="getWeatherIcon(forecast.text_day)" class="forecast-icon" />
            </div>
            <div class="right-info">
              <div class="weather-text">
                <span>{{ forecast.text_day }}</span>
                <span v-if="forecast.text_day !== forecast.text_night" class="night-text">
                  转{{ forecast.text_night }}
                </span>
              </div>
              <div class="temp-range">{{ forecast.high }}° / {{ forecast.low }}°</div>
              <div class="wind">
                {{ forecast.wd_day }} {{ forecast.wc_day }}
                <template v-if="forecast.wd_day !== forecast.wd_night">
                  <br />转{{ forecast.wd_night }} {{ forecast.wc_night }}
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";
import sunnyIcon from "../../../assets/images/weather-icons/sunny.png";
import cloudyIcon from "../../../assets/images/weather-icons/cloudy.png";
import overcastIcon from "../../../assets/images/weather-icons/overcast.png";
import lightRainIcon from "../../../assets/images/weather-icons/light-rain.png";
import moderateRainIcon from "../../../assets/images/weather-icons/moderate-rain.png";
import heavyRainIcon from "../../../assets/images/weather-icons/heavy-rain.png";
import stormIcon from "../../../assets/images/weather-icons/storm.png";
import snowIcon from "../../../assets/images/weather-icons/snow.png";
import fogIcon from "../../../assets/images/weather-icons/fog.png";
import unknownIcon from "../../../assets/images/weather-icons/unknown.png";

interface WeatherForecast {
  date: string;
  week: string;
  high: number;
  low: number;
  wc_day: string;
  wc_night: string;
  wd_day: string;
  wd_night: string;
  text_day: string;
  text_night: string;
}

const props = defineProps<{
  forecasts?: WeatherForecast[];
  area?: string;
}>();

const tempChartRef = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return {
    date: `${date.getMonth() + 1}月${date.getDate()}日`,
  };
};

const getWeatherIcon = (text: string) => {
  const iconMap: Record<string, string> = {
    晴: sunnyIcon,
    多云: cloudyIcon,
    阴: overcastIcon,
    小雨: lightRainIcon,
    中雨: moderateRainIcon,
    大雨: heavyRainIcon,
    暴雨: stormIcon,
    雪: snowIcon,
    雾: fogIcon,
  };
  return iconMap[text] || unknownIcon;
};

const initChart = () => {
  if (!tempChartRef.value || !props.forecasts) return;

  // 确保容器尺寸已经计算完成
  const container = tempChartRef.value;
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    setTimeout(initChart, 100);
    return;
  }

  if (!chart) {
    chart = echarts.init(tempChartRef.value);
  }

  const dates = props.forecasts.map((f) => formatDate(f.date).date);
  const highTemps = props.forecasts.map((f) => f.high);
  const lowTemps = props.forecasts.map((f) => f.low);

  const option: EChartsOption = {
    title: {
      text: `${props.area}未来温度趋势`,
      left: "center",
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#303133",
      },
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "rgba(64, 158, 255, 0.2)",
      borderWidth: 1,
      textStyle: {
        color: "#606266",
      },
      padding: [8, 12],
      formatter: (params) => {
        return `${params[0].name}<br/>
                最高温：${params[0].value}°C<br/>
                最低温：${params[1].value}°C`;
      },
    },
    legend: {
      data: ["最高温", "最低温"],
      top: 40,
      textStyle: {
        color: "#606266",
      },
      itemGap: 20,
    },
    grid: {
      top: 80,
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 0,
        color: "#909399",
        fontSize: 12,
      },
      axisLine: {
        lineStyle: {
          color: "#E4E7ED",
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#F2F6FC",
          type: "dashed",
        },
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "{value}°C",
        color: "#909399",
        fontSize: 12,
      },
      axisLine: {
        lineStyle: {
          color: "#E4E7ED",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#F2F6FC",
        },
      },
    },
    series: [
      {
        name: "最高温",
        type: "line",
        data: highTemps,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        itemStyle: {
          color: "#FF6B6B",
          borderWidth: 2,
          borderColor: "#fff",
          shadowColor: "rgba(255, 107, 107, 0.3)",
          shadowBlur: 10,
        },
        lineStyle: {
          width: 3,
          shadowColor: "rgba(255, 107, 107, 0.2)",
          shadowBlur: 10,
        },
        label: {
          show: true,
          formatter: "{c}°",
          fontSize: 12,
          fontWeight: "bold",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(255, 107, 107, 0.2)",
              },
              {
                offset: 1,
                color: "rgba(255, 107, 107, 0)",
              },
            ],
          },
        },
      },
      {
        name: "最低温",
        type: "line",
        data: lowTemps,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        itemStyle: {
          color: "#4ECDC4",
          borderWidth: 2,
          borderColor: "#fff",
          shadowColor: "rgba(78, 205, 196, 0.3)",
          shadowBlur: 10,
        },
        lineStyle: {
          width: 3,
          shadowColor: "rgba(78, 205, 196, 0.2)",
          shadowBlur: 10,
        },
        label: {
          show: true,
          formatter: "{c}°",
          fontSize: 12,
          fontWeight: "bold",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(78, 205, 196, 0.2)",
              },
              {
                offset: 1,
                color: "rgba(78, 205, 196, 0)",
              },
            ],
          },
        },
      },
    ],
  };

  chart.setOption(option);
};

watch(
  () => props.forecasts,
  () => {
    nextTick(() => {
      initChart();
    });
  },
  { deep: true }
);

const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  chart?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style lang="scss" scoped>
.forecast-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: row;
  gap: 20px;
  overflow: hidden;

  .chart-wrapper {
    flex: 3;
    min-height: 350px;
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    }

    .temp-chart {
      height: 100%;
      width: 100%;
    }
  }

  .forecast-wrapper {
    flex: 2;
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    }

    .forecast-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      height: 100%;
      overflow-y: auto;
      padding-right: 8px;

      .forecast-item {
        width: 100%;
        padding: 16px;
        background: linear-gradient(145deg, #f8f9fa, #ffffff);
        border-radius: 10px;
        border: 1px solid rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 8px 16px rgba(64, 158, 255, 0.1);
          border-color: rgba(64, 158, 255, 0.2);
        }

        .date {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 12px;
          padding: 0 10px;
          border-bottom: 1px dashed rgba(0, 0, 0, 0.06);
          padding-bottom: 8px;

          .day {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
            letter-spacing: 0.5px;
          }

          .week {
            font-size: 14px;
            color: #909399;
            background: #f0f2f5;
            padding: 2px 8px;
            border-radius: 4px;
          }
        }

        .info-wrapper {
          display: flex;
          align-items: center;
          gap: 15px;
          padding: 0 10px;

          .left-info {
            flex-shrink: 0;

            .forecast-icon {
              width: 40px;
              height: 40px;
              filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
            }
          }

          .right-info {
            flex: 1;

            .weather-text {
              color: #606266;
              margin-bottom: 6px;
              font-size: 15px;
              display: flex;
              align-items: center;
              gap: 8px;

              .night-text {
                color: #909399;
                font-size: 13px;
                padding: 2px 6px;
                background: #f0f2f5;
                border-radius: 4px;
              }
            }

            .temp-range {
              color: #409eff;
              font-size: 18px;
              font-weight: bold;
              margin-bottom: 6px;
              text-shadow: 0 1px 2px rgba(64, 158, 255, 0.2);
            }

            .wind {
              color: #909399;
              font-size: 13px;
              line-height: 1.4;
              display: inline-block;
              background: #f0f2f5;
              padding: 4px 8px;
              border-radius: 4px;
            }
          }
        }
      }
    }
  }
}
</style>
